package com.kwlt.smc.dao;

import java.util.Date;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.kwlt.smc.entity.SmsSendDetail;
import com.kwlt.smc.util.ConUtils;


@Component
public class SmsSendDetailDaoImpl implements SmsSendDetailDao {

	@PersistenceContext
	private EntityManager em;
	
	@Override
	@Transactional(readOnly = false)
	public void save(List<SmsSendDetail> list,String date) {
		String tableName = "sms_send_detail_"+date;
		insert(list,tableName);
	}
	
	private void insert(List<SmsSendDetail> list,String tableName){
		if(list!=null && list.size()>0){
			StringBuffer sql = new StringBuffer();
			sql.append("INSERT INTO ").append(tableName).append("(");
			sql.append("PHONE_NUMBER,SEND_DATE,SEND_SUCCESS_FLAG,RPT_FLAG,RPT_VALUE,USER,RPT_DATE,USER_DATE,");
			sql.append("CHANNEL,INT_SUBMIT_DATE,SEND_RESP_CODE,INT_MSG_ID,LOCAL_MSG_ID,OPER_BAK_MSG_ID,OPERATORS,EXT_PARM1,EXT_PARM2,EXT_PARM3,EXT_PARM4) VALUES  ");
			for(int i=0;i<list.size();i++){
				SmsSendDetail po = list.get(i);
				sql.append("('"+po.getPhoneNum()).append("',");
				sql.append(po.getSendDate()==null?"null":"'"+ConUtils.formatDate(po.getSendDate(), "yyyyMMddHHmmss")+"'").append(",");
				sql.append(po.getSendSuccessFlag()==null?"null":"'"+po.getSendSuccessFlag()+"'").append(",");
				sql.append(po.getRptFlag()==null?"null":"'"+po.getRptFlag()+"'").append(",");
				sql.append(po.getRptValue()==null?"null":"'"+po.getRptValue()+"'").append(",");
				sql.append(po.getUser()==null?"null":"'"+po.getUser()+"'").append(",");
				sql.append(po.getRptDate()==null?"null":"'"+ConUtils.formatDate(po.getRptDate(), "yyyyMMddHHmmss")+"'").append(",");
				sql.append(po.getUserDate()==null?"null":"'"+po.getUserDate()+"'").append(",");
				sql.append(po.getChannel()==null?"null":"'"+po.getChannel()+"'").append(",");
				sql.append(po.getIntSubmitDate()==null?"null":"'"+ConUtils.formatDate(po.getIntSubmitDate(), "yyyyMMddHHmmss")+"'").append(",");
				sql.append(po.getSendRespCode()==null?"null":"'"+po.getSendRespCode()+"'").append(",");
				sql.append(po.getIntMsgId()==null?"null":"'"+po.getIntMsgId()+"'").append(",");
				sql.append(po.getLocalMsgId()==null?"null":"'"+po.getLocalMsgId()+"'").append(",");
				sql.append(po.getOperBakMsgId()==null?"null":"'"+po.getOperBakMsgId()+"'").append(",");
				sql.append(po.getOperators()==null?"null":"'"+po.getOperators()+"'").append(",");
				sql.append(po.getExtParm1()==null?"null":"'"+po.getExtParm1()+"'").append(",");
				sql.append(po.getExtParm2()==null?"null":"'"+po.getExtParm2()+"'").append(",");
				sql.append(po.getExtParm3()==null?"null":"'"+po.getExtParm3()+"'").append(",");
				sql.append(po.getExtParm4()==null?"null":"'"+po.getExtParm4()+"'");
				sql.append(")");
				if(list.size()-i>1){
					sql.append(",");
				}
			}
			Session session=null;
			try {
				session = (Session) em.getEntityManagerFactory().createEntityManager().getDelegate();
				Transaction tc = session.beginTransaction();
				org.hibernate.Query createQuery = session.createSQLQuery(sql.toString());
				createQuery.executeUpdate();
				tc.commit();
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				if(session!=null){
					session.clear();
					session.close();
				}
			}
		}
	}

	@Override
	public SmsSendDetail findSmsSendDetailByLocalMsgId(String msgId,String phoneNum,String dateStr) {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT * FROM ").append("sms_send_detail_" + dateStr);
		sql.append(" where local_msg_id='" + msgId + "' and phone_number='"+phoneNum+"' ");
		SmsSendDetail sd=null;
		try {
			List list = em.createNativeQuery(sql.toString()).getResultList();
			if (list.isEmpty()) {
				return null;
			} else{
				Object[] obj = (Object[]) list.get(0);
				sd = new SmsSendDetail();
				sd.setSmsSendDetailId(new Long(String.valueOf(obj[0])));
				sd.setUser(String.valueOf(obj[6]));
				sd.setIntMsgId(String.valueOf(obj[12]));
				return sd;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public int updateSmsRpt(SmsSendDetail smsSendDetail,String dateStr) {
		StringBuffer sql = new StringBuffer();
		sql.append("UPDATE ").append("sms_send_detail_" + dateStr);
		sql.append(" SET rpt_flag='"
				+ smsSendDetail.getRptFlag() + "'");
		sql.append(",rpt_value='" + smsSendDetail.getRptValue() + "'");
		sql.append(",rpt_date='" +  smsSendDetail.getRptDateStr() + "'");
		sql.append(",OPER_BAK_MSG_ID='" +  smsSendDetail.getOperBakMsgId() + "'");
		if(smsSendDetail.getSendDate()!=null){
			sql.append(",send_date='" +  smsSendDetail.getSendDateStr() + "'");
		}
		sql.append(" WHERE local_msg_id = '").append(smsSendDetail.getLocalMsgId() + "'");
		sql.append(" and phone_number = '").append(smsSendDetail.getPhoneNum() + "'");
		try {
			return em.createNativeQuery(sql.toString()).executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		} 
	}
	
	public List query(String sql) {
		List result = em.createNativeQuery(sql.toString()).getResultList();
		return result;
	}
	
	/**
	 * create table
	 * @param tableName 表名称
	 * @throws Exception 
	 */
	public void create(String tableName) throws Exception{
		StringBuffer sql = new StringBuffer();
		sql.append("CREATE TABLE IF NOT EXISTS ").append(tableName);
		sql.append(" LIKE sms_send_detail_yyyymmdd");
		try {
			em.createNativeQuery(sql.toString()).executeUpdate();
		} catch (Exception e) {
			throw e;
		}
	}
}
